﻿using System;
using System.Data.Objects;

namespace EFObjectContextScope
{
    internal class ObjectContextData<TObjectContext> : IDisposable where TObjectContext : ObjectContext
    {
        // Fields
        internal ObjectContextScope<TObjectContext> CurrentScope;
        internal ObjectContextWrapper<TObjectContext> CurrentObjectContextWrapper;

        [ThreadStatic]
        private static ObjectContextData<TObjectContext> staticData;

        private bool disposed = false;

        // Properties
        internal static ObjectContextData<TObjectContext> CurrentData
        {
            get
            {
                ObjectContextData<TObjectContext> staticData = ObjectContextData<TObjectContext>.staticData;
                if (staticData == null)
                {
                    staticData = new ObjectContextData<TObjectContext>();
                    ObjectContextData<TObjectContext>.staticData = staticData;
                }
                return staticData;
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (!this.disposed)
            {
                this.disposed = true;

                CurrentScope.Dispose();
                CurrentScope = null;

                CurrentObjectContextWrapper.Dispose();
                CurrentObjectContextWrapper = null;

                staticData.Dispose();
                staticData = null;
            }
        }

        #endregion
    }
}
